//
//  HWTabBar.swift
//  WeiBo
//
//  Created by macbook on 16/6/28.
//  Copyright © 2016年 buWangChuXing. All rights reserved.
//

import UIKit


//声明协议
//swift 中需要遵守NSObjectProtocol协议
protocol HWTabBarDelegate:NSObjectProtocol{

    //声明协议方法
    func btnPushController()
}


class HWTabBar: UITabBar {

    //声明代理
    weak var HWDelegate:HWTabBarDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        //求出item的宽度
        let winth = KScreenW / 5
        
        var index:CGFloat = 0
        //拿到按钮设置每个按钮的位置
        for itembtn in self.subviews{
     
            if itembtn.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                
                //设置宽度
                itembtn.frame.size.width = winth
                itembtn.frame.origin.x = index * winth
                
                index++
                if index == 2 {
                    index++
                }
            }
        }
        
        
    
        
        but.center.x = self.frame.size.width * 0.5
        but.center.y = self.frame.size.height * 0.5
    }
    
    func setupUI(){
    
    addSubview(but)
    }
    
    
    //懒加载创建一个中间按钮 并添加背景图及自动填充大小
    private lazy var but:UIButton = {
    
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named:"tabbar_compose_button_highlighted"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named:"tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        
        btn.setImage(UIImage(named:"tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named:"tabbar_compose_icon_add"), forState: UIControlState.Highlighted)
        btn.addTarget(self, action: #selector(HWTabBar.btnClick), forControlEvents: UIControlEvents.TouchUpInside)
        btn.sizeToFit()
        
        return btn
        
    }()
 
    //中间按钮的点击事件
  @objc private  func btnClick(){
    
    HWDelegate?.btnPushController()
        
    }
    
}
